﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Security;
using System.Web.Mvc;
using CoolCode.Ioc;
using CoolCode.Services;
using CoolCode.Web.Security;

namespace CoolCode.Web.Mvc
{
	public class ControllerBase : Controller
	{
		protected bool WithLog = false;
		 
		public string UserID
		{
			get { return User.Identity.Name; }
		}

		public string Title
		{
			set
			{
				ViewData["Page_Title"] = value;
			}
		}

		public T NewModel<T>() where T : new()
		{
			T entity = new T();
			ITrackEntity t = entity as ITrackEntity;
			if (t != null)
			{
				t.CreateUser = UserID;
				t.UpdateUser = UserID;
				t.CreateDate = DateTime.Now;
				t.UpdateDate = DateTime.Now;
			}
			return entity;
		}

		//public T NewModel<T>() where T : ITrackEntity, new()
		//{
		//    T t = new T();
		//    t.CreateUser = UserID;
		//    t.UpdateUser = UserID;
		//    t.CreateDate = DateTime.Now;
		//    t.UpdateDate = DateTime.Now;
		//    return t;
		//}

		public void MaskUpdated<T>(T t) where T : ITrackEntity
		{
			t.UpdateUser = UserID;
			t.UpdateDate = DateTime.Now;
			if (t.CreateUser == null)
			{
				t.CreateUser = UserID;
			}
			if (t.CreateDate <= Config.MinDate)
			{
				t.CreateDate = DateTime.Now;
			}
		}

		public T RetrieveModel<T>() where T : class, new()
		{
			T model = new T();
			TryUpdateModel<T>(model);
			return model;
		}

		#region Services

		private ITrackService _TrackService;
		public ITrackService TrackService
		{
			get
			{
				if (_TrackService == null)
				{
					_TrackService = Digger.Dig<ITrackService>();
				}
				return _TrackService;
			}
		}

		private IMembership _MembershipService;
		public IMembership MembershipService
		{
			get
			{
				if (_MembershipService == null)
				{
					_MembershipService = Digger.Dig<IMembership>();
				}
				return _MembershipService;
			}
		}
		private IFormsAuthentication _FormsAuthenticationService;
		public IFormsAuthentication FormsAuthenticationService
		{
			get
			{
				if (_FormsAuthenticationService == null)
				{
					_FormsAuthenticationService = Digger.Dig<IFormsAuthentication>();
				}
				return _FormsAuthenticationService;
			}
		}

		#endregion

		protected static readonly IDiggable Digger = InjectTable.GetDigger();

		protected static readonly ILogger Logger = LogManager.GetLogger(typeof(ControllerBase));

		public ControllerBase()
		{
			ViewData["starttime"] = DateTime.Now;
			LogManager.Config(); 
			bool.TryParse(System.Configuration.ConfigurationManager.AppSettings["Log"], out WithLog); 
			//string log4netConfig = System.Configuration.ConfigurationManager.AppSettings["log"];
			//log4netConfig = System.Web.HttpContext.Current.Server.MapPath(log4netConfig);
			//LogManager.Config(log4netConfig);
		}

		public void LogError(Exception ex)
		{
			Logger.Error(ex);
		}

		protected override void OnException(ExceptionContext filterContext)
		{
			if (WithLog)
			{
				string error = string.Format("系统出现未处理错误:\r\n\tUser:{0},Controller:{1}, Action: {2}, RouteData:{3}\r\n\t",
					filterContext.HttpContext.User.Identity.Name,
					filterContext.Controller,
					filterContext.RouteData.Values["action"],
					filterContext.RouteData.GetInformation()
				);
				Logger.Error(error, filterContext.Exception);
			}
			base.OnException(filterContext);
		}

		public ActionResult RedirectToError(string msg)
		{
			//  return Error(msg);
			return RedirectToAction("Error", new { id = msg });
		}

		public ActionResult RedirectToNotFound()
		{
			return RedirectToAction("NotFound");
		}

		public ActionResult NotFound()
		{
			return View();
		}
		 
		public ActionResult Error(string id)
		{
			Title = "错误信息";
			ViewData["Message"] = id;
			return View();
		}

	}


}
